<style lang="css">
  @import "../assets/css/CodeMirror.css";
  .editor-wrap {
  width: 100%;
  height: 100%;
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  }
  .editor-wrap .CodeMirror {
    height: 100%;
  }
  /*编辑题目*/
  .editor-wrap .editor {
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
    height: -webkit-calc(100% - 40px);
    height: calc(100% - 40px);
    border: 1px solid #e0e0e0;
    margin-top: 10px;
    background: #fff;
  }
  /*编辑区*/
  .editor-wrap .action-bar {
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    height: 52px;
    background-color: #fff;
    border: 1px solid #e0e0e0;
    padding: 0 20px;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .editor-wrap .action-bar:hover .btn-tmpl {
    opacity: 1;
  }
  .editor-wrap .action-bar>span{
    font-size: 18px;
    color: #159af1;
    font-weight: bold;
    margin-right: 10px;
  }
  .editor-wrap .action-bar>.see{
    font-size: 14px;
    color: #222222;
    font-weight: bold;
  }
  .editor-wrap .action-bar>.yellow{
    font-size: 12px;
    color: #ffa400 !important;
    margin-left: -10px;
  }
  .editor-wrap .action-bar .btn {
    font-size: 14px;
    color: #222;
    padding-left: 10px;
    padding-right: 10px;
    cursor: pointer;
  }
  .editor-wrap .action-bar .btn-tmpl {
    opacity: 0;
    -webkit-transition: all 0.15s ease-in-out;
    transition: all 0.15s ease-in-out;
    padding-left: 5px;
    padding-right: 5px;
  }
  .editor-wrap .action-bar .space {
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
  }

</style>
<template>
  <section class="editor-wrap">
    
    <div class="action-bar">
      <span>编辑区</span>
      <a class="btn btn-link btn-sample see" @click="sample=true" v-show="!sample">查看样例</a>
      <el-tooltip class="item" effect="dark" content="此操作会将编辑区域重置为样例内容" placement="top-start">
        <a class="btn btn-link btn-sample yellow" @click="pasteSample" v-show="!sample">将样例内容粘贴到编辑区</a>
      </el-tooltip>
      <a class="btn btn-link btn-sample" @click="addSample(0)" v-show="!sample">单选</a>
      <a class="btn btn-link btn-sample" @click="addSample(1)" v-show="!sample">多选</a>
      <a class="btn btn-link btn-sample" @click="addSample(2)" v-show="!sample">不定项</a>
      <a class="btn btn-link btn-sample" @click="addSample(3)" v-show="!sample">判断</a>
      <a class="btn btn-link btn-sample" @click="addSample(4)" v-show="!sample">填空</a>
      <a class="btn btn-link btn-sample" @click="addSample(5)" v-show="!sample">问答</a>

      <a class="btn btn-link btn-edit" @click="sample=false" v-show="sample"><i class="fa fa-angle-left"></i> 返回编辑</a>
      <a class="btn btn-link btn-sample" @click="showSampleHint=true" v-show="sample && !showSampleHint">显示说明</a>
      <a class="btn btn-link btn-sample" @click="showSampleHint=false" v-show="sample && showSampleHint">隐藏说明</a>
    </div>
    <div class="editor" ref="editor"></div>
  </section>
</template>
<script>
  import CodeMirror from 'codemirror'
  import Parser from '../assets/js/parser'
  import store from 'store'
  import _ from 'lodash'
  import '../assets/js/mode-questions'
 let strType = `题型：单选
知识点：常识
题目难度：中`;
  const sampleTemplate = [
    `
1.[单选]服务商主动申请微应用服务退出钉钉应用市场的需提前多少天向钉钉开放平台申请？
A.90天
B.120天
C.60天
D.30天
答案：A
解析：很明显是90天。`,
`2.[多选]当ISV发生P1级级数故障时，钉钉应用市场将作出的处罚措施是？
A.罚款20000元
B.下架30天
C.扣分12分
D.扣分6分
答案：ABC`,
`3.[不定项]以下说法正确的有？
A.7月有30天
B.8月有30天
C.2014年2月有28天
D.2月有28天
答案：C`,
`4.[判断]在微应用中需要用户二次登陆，需要用户输入账号、密码，这种行为是否正确？
答案：正确`,
`5.[填空]中国最顶级的三家互联网公司常常合称为BAT，他们分别是: __ ， __ ，和 __ 。
填空数：3
答案形式：仅顺序不一致
参考答案1：百度|||baidu
参考答案2：阿里|||阿里巴巴
参考答案3：腾讯|||QQ`,
`6.[问答]一年哪几个月有31天？
参考答案：1月、3月、5月、7月、8月、10月、12月
题目难度：难`];

  let editor = null
  let parser = null
  export default {
    data () {
      return {
        questions: [],
        qType: ["单选", "多选", "不定项", "判断", "问答", "填空"],
        value: store.get('editor') || '',
        sample: false, // 样例模式
        showSampleHint: true
      }
    },
    mounted() {
      let self = this
      //初始化编辑器
      editor = CodeMirror(this.$refs.editor, {
        textWrapping: true,
        lineNumbers: true,
        tabMode: 'spaces',
        lineWrapping: 'true',
        mode: 'questions',
        theme: 'editor',
        indentUnit: 4,
        value: store.get('editor') || '',
        cursorHeight: .7,
        autofocus: true,
        pollInterval: 1000,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-hintgutter']
      })
      //初始化解析器
      parser = new Parser(editor, {
        delay: 500,
        onChange() {
          self.value = editor.getValue()
          if (!self.sample) {
            store.set('editor', self.value)
          }
          self.questions = parser.data.questions
          self.$emit('update', parser.data)
        }
      })
      //编辑器和预览器滚动实时联动
      editor.on('scroll', function (cm) {
        let info = cm.getScrollInfo()
        let percent = info.top / (info.height - info.clientHeight) // 分母为零不会触发scroll
        self.$emit('scroll', percent)
      })

      CodeMirror.signal(editor, 'change')

    },
    watch: {
      sample: {
        immediate: true,
        handler(val){
          this.sampleChild = val;
          this.$nextTick(function () {
            editor.setOption('readOnly', val)
            if (val) {
              editor.setValue(strType+sampleTemplate.join("\n"))
              // editor.setValue(sampleTemplate)
              editor.setOption('theme', 'sample-editor')
              parser.setSample(this.showSampleHint)
            } else {
              editor.setValue(store.get('editor') || '')
              editor.setOption('theme', 'editor')
              parser.setSample(false)
            }
          })
        }
      },
      showSampleHint(val){
        if (this.sample) {
          parser.setSample(val)
          CodeMirror.signal(editor, 'change')
        }
      }
    },
    events: {
      'scroll-question'(qIndex) {
        this.scrollTo(qIndex)
      },
      'editor-clear'(){
        editor.setValue('')
      }
    },
    methods: {
      scrollTo(qIndex){
        let v = this.questions[qIndex]
        if (v) {
          editor.scrollIntoView({line: v.ui.line}, 20)
        }
      },
      pasteSample(){
        // editor.setValue(sampleTemplate)
        editor.setValue(strType+sampleTemplate.join("\n"))
      },
      addSample(index){
        let content = sampleTemplate[index];
        editor.setValue(editor.getValue()+'\n'+content);
        editor.execCommand("goDocEnd");
      },
      checkData(){
        let errMsg

        if (!this.questions.length) {
          return '没有题目数据'
        }

        _.each(this.questions, function (v, index) {
          if (v._hasError) {
            errMsg = `第${index + 1}题有问题，请按提示检查`
            editor.scrollIntoView({line: v.ui.line}, 20)
            return false
          }
        })
        return errMsg
      },
      getFormattedData(){
        this.sample = false
        let errMsg = this.checkData()
        if (errMsg) {
          return {
            err: errMsg
          }
        }
        return {
          data: this.questions
        }
      }
    },

  }
</script>
